package com.gitee.aleenjava.aliyun.mqtt.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.UUID;

/**
 * @author cheng
 */
@Data
@ConfigurationProperties(prefix = "mqtt.subscriber")
public class MqttSubscriberProperties {
    /**
     * 是否开启mqtt客户端
     */
    private boolean enable = false;
    /**
     * mqtt broker ip
     */
    private String ip;

    /**
     * mqtt broker 端口
     */
    private String port;

    /**
     * MQ4IOT 实例 ID，购买后控制台获取
     */
    private String instanceId;
    /**
     * 账号 accesskey，从账号系统控制台获取
     */
    private String accessKey;
    /**
     * 账号 secretKey，从账号系统控制台获取，仅在Signature鉴权模式下需要设置
     */
    private String secretKey;

    /**
     * mqtt 客户端id是否随机生成
     */
    private boolean enableRandomClientId = true;

    /**
     * mqtt 客户端id
     */
    private String clientId;

    /**
     * 连接超时时间(秒)
     */
    private int connectionTimeout = 5;

    /**
     * 是否是临时会话, 客户端断开broker不再推送
     */
    private boolean enableCleanSession = true;

    /**
     * 消费客户端重连最大次数
     */
    private int clientReconnectCount = 5;

    /**
     * 消费客户端重连间每次隔时间(毫秒)
     */
    private int clientReconnectIntervalTime = 100;

    @PostConstruct
    private void init() {
        if (enable) {
            String prefix = this.getClass().getAnnotation(ConfigurationProperties.class).prefix();
            Assert.hasText(ip, "No mqtt broker IP configured in subscriber {" + prefix + ".ip}");
            Assert.hasText(port, "No mqtt broker port configured in subscriber : {" + prefix + ".port}");
            if (enableRandomClientId) {
                clientId = UUID.randomUUID().toString().replaceAll("-", "");
            } else if (!StringUtils.hasText(clientId)) {
                throw new IllegalArgumentException("is the mqtt client ID randomly generated? When configured as false, the mqtt client ID is not configured in subscriber: {" + prefix + ".port}");
            }
        }
    }

}
